import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, Select, InputNumber, Switch, Upload, Button, Radio, DatePicker, Icon, message } from 'antd';
import moment from 'moment';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState, useEffect } from 'react';
import { TwitterPicker } from 'react-color';
import reactCSS from 'reactcss';
import TextArea from 'antd/lib/input/TextArea';
import { formatMessage } from 'umi-plugin-react/locale';
import { DATEIME_FORMAT, getBdToken } from '@/utils/BdHelper';
import { ConfigListItem } from '../data';
import Img from '@/components/Img';
import PreviewForm from '@/components/PreviewForm';
const FormItem = Form.Item;

export interface FormValueType extends Partial<ConfigListItem> {
  id?: number;
  name?: string;
  remark?: string;
  type?: string;
  nickame?: string;
  rank_num?: string;
}

interface ConfigFormProps extends FormComponentProps {
  modalVisible: boolean;
  otherValues: any;
  values: Partial<ConfigListItem>;
  onSubmit: (fieldsValue: FormValueType) => Promise<any>;
  onCancel: () => void;
  changeParamType: () => void;
  handleChangeType: (value: any) => void;
  handleSetPicture: (value: any) => void;
  handleSetColor: (value: any) => void;
}

const ConfigForm: React.FC<ConfigFormProps> = props => {

  const [displayColorPicker, setDisplayColorPicker] = useState<boolean>(false);
  const [pictureModalVisible, setPictureModalVisible] = useState<boolean>(false);
  const [picturePreviewUrl, setPicturePreviewUrl] = useState<string>('');
  const { modalVisible, form, onSubmit: handleSubmit, onCancel, otherValues, values, handleChangeType, handleSetPicture, handleSetColor } = props;
  const { isUpdate, radioType, picture, color } = otherValues;
  const token = getBdToken();
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');
  const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
  const colorStyles = reactCSS({
    'default': {
      color: {
        width: '36px',
        height: '14px',
        borderRadius: '2px',
        background: `${color}`,
      },
      swatch: {
        marginTop: '8px',
        padding: '5px',
        background: '#fff',
        borderRadius: '1px',
        boxShadow: '0 0 0 1px rgba(0,0,0,.1)',
        display: 'inline-block',
        cursor: 'pointer',
      },
      popover: {
        position: 'absolute',
        zIndex: '2',
      },
      cover: {
        position: 'fixed',
        top: '0px',
        right: '0px',
        bottom: '0px',
        left: '0px',
      },
    },
  });

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      // form.resetFields();
      switch (radioType) {
        case 'switch':
          fieldsValue.content = fieldsValue.content_switch.toString();
          break;
        case 'date':
          fieldsValue.content = fieldsValue.content_date.toString();
          break;
        case 'file':
          if (picture.length > 0) {
            if (picture[0].response && picture[0].response.code === 0) {
              // todo: code != 0 时的提示
              fieldsValue.content = picture[0].response.data.file_url;
            } else {
              fieldsValue.content = picture[0].url;
            }
          }
          // else{
          //   message.error('请上传图片');
          //   return;
          // }
          break;
        default:
      }

      if (isUpdate) {
        fieldsValue.id = values.id;
      }
      handleSubmit(fieldsValue).then(success => {
        if (success) {
          form.resetFields();
        }
      });
    });
  };

  const handleChangeColor = (colorObj: any) => {
    form.setFieldsValue({ 'content': colorObj.hex });
    handleSetColor(colorObj.hex);
  }

  const previewPicture = (file: any) => {
    setPicturePreviewUrl(file.thumbUrl);
    setPictureModalVisible(true);
  }
  const handleSubmitDataForm = (value: any) => {
    setSelectImg(value[0].oss_url);
    handleDataModalVisible(false)
  }
  console.log('type--->', radioType)
  const [selectImg, setSelectImg] = useState('');
  useEffect(() => {
    setSelectImg(isUpdate ? values.file_url : '');
  }, []);
  return (
    <Modal
      destroyOnClose
      title="新增配置"
      width='60%'
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'图片'}>
        {form.getFieldDecorator('file_url', {
          initialValue: isUpdate ? values.file_url : '',
          //rules: [{ required: true, message: formatMessage({ id: 'app.base.verify.variable-title' }) }],
        })(<>
          {selectImg != '' ? <img src={selectImg} onClick={() => {
            setPreviewImg(selectImg)
            handlePreviewModalVisible(true)
          }} alt="" style={{ width: 100, marginRight: 20 }} /> : null}
          <Button onClick={() => {
            handleDataModalVisible(true)
          }}>
            选择图片
        </Button>
        </>)}
      </FormItem>
      <Img
        dataImgModalVisible={dataModalVisible}
        onSubmit={async formValue => handleSubmitDataForm(formValue)}
        onCancel={() => handleDataModalVisible(false)}
      />
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.group' })}>
        {form.getFieldDecorator('config_group_id', {
          initialValue: isUpdate ? values.config_group_id?.toString() : otherValues.selectIndex,
          rules: [{ required: true, message: formatMessage({ id: 'app.base.verify.group' }) }],
        })(
          <Select
            showSearch
            placeholder={formatMessage({ id: 'app.base.choose' })}
            style={{ width: '100%' }}
            disabled
          >
            {
              otherValues.common.sideBarList &&
              otherValues.common.sideBarList.map((d: any) => <Select.Option key={d.id} value={(d.id).toString()}>{d.name}</Select.Option>
              )
            }
          </Select>
        )}
      </FormItem>


      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.variable-type' })}>
        {form.getFieldDecorator('type', {
          initialValue: isUpdate ? values.type : radioType,
          rules: [],
        })(
          <Radio.Group buttonStyle="solid" onChange={(e) => handleChangeType(e.target.value)} disabled={isUpdate}>
            {
              otherValues.common.typeSelectOption &&
              otherValues.common.typeSelectOption.map(
                (d: any) => <Radio.Button key={d.key} value={d.key}>{d.text}</Radio.Button>
              )
            }
          </Radio.Group>
        )}
      </FormItem>

      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.variable-title' })}>
        {form.getFieldDecorator('name', {
          initialValue: isUpdate ? values.name : '',
          rules: [{ required: true, message: formatMessage({ id: 'app.base.verify.variable-title' }) }],
        })(<Input />)}
      </FormItem>

      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.variable-identification' })}>
        {form.getFieldDecorator('nickname', {
          initialValue: isUpdate ? values.nickname : '',
          rules: [{ required: true, message: formatMessage({ id: 'app.base.verify.variable-identification' }) }],
        })(<Input disabled={isUpdate} />)}
      </FormItem>

      {
        radioType === 'switch' &&
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.switch' })}>
          {form.getFieldDecorator('content_switch', {
            initialValue: isUpdate ? 'true' === values.content ? true : false : true,
            valuePropName: 'checked',
            rules: [],
          })(<Switch checkedChildren={formatMessage({ id: 'app.base.is-enable.true' })} unCheckedChildren={formatMessage({ id: 'app.base.is-enable.close' })} />)}
        </FormItem>
      }

      {
        radioType === 'date' &&
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.time' })}>
          {form.getFieldDecorator('content_date', {
            initialValue: isUpdate ? moment(values.content) : '',
            rules: [{ required: true, message: formatMessage({ id: 'app.base.verify.time' }) }],
          })(<DatePicker format={DATEIME_FORMAT} style={{ width: '100%' }} placeholder="" />)}
        </FormItem>
      }

      {
        radioType === 'color' &&
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.color' })}>
          <div style={colorStyles.swatch} onClick={() => setDisplayColorPicker(!displayColorPicker)}>
            <div style={colorStyles.color} ></div>
          </div>
          {displayColorPicker ?
            <div style={{ position: 'absolute', zIndex: 2 }}>
              <div style={{ position: 'fixed', top: '0px', right: '0px', bottom: '0px', left: '0px' }} onClick={() => setDisplayColorPicker(false)}></div>
              <TwitterPicker color={color} onChange={(val) => handleChangeColor(val)} />
            </div>
            : null
          }
        </Form.Item>
      }

      {
        (radioType === 'string' || radioType === 'color') &&
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.variable-value' })}>
          {form.getFieldDecorator('content', {
            initialValue: isUpdate ? values.content : '#1890ff',
            rules: [{ required: true, message: formatMessage({ id: 'app.base.verify.variable-value' }) }],
          })(<TextArea rows={5} disabled={false} placeholder="" />)}
        </FormItem>
      }

      {
        radioType === 'file' &&
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.switch.file' })}>
          {form.getFieldDecorator('picture', {
            initialValue: isUpdate ? otherValues.picture : '',
            // rules: [{required: true, message: '请上传图片'}],
          })(
            <Upload
              {...{ listType: 'picture', className: 'upload-list-inline', }}
              action="/api/admin/file/upload"
              defaultFileList={otherValues.picture}
              beforeUpload={(file) => {
                console.log('before upload file type:', file.type)
                // todo: 这里可以对上传文件类型做限制
                return true;
              }}
              data={{ type: 'image' }}
              onRemove={() => handleSetPicture([])}
              onChange={(changeObj) => handleSetPicture(changeObj.fileList)}
              onPreview={previewPicture}
              headers={{
                Authorization: `Bearer ${token}`,
              }}
            >
              {
                picture.length === 0 ? (
                  <Button>
                    <Icon type="upload" /> {formatMessage({ id: 'app.base.upload' })}
                  </Button>
                ) : null
              }
            </Upload>
          )}
        </FormItem>
      }

      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.sort' })}>
        {form.getFieldDecorator('rank_num', {
          initialValue: 888,
          rules: [{ required: true, message: formatMessage({ id: 'app.base.verify.sort' }) }],
        })(<InputNumber style={{ width: '100%' }} placeholder={formatMessage({ id: 'app.base.placeholder.sort' })} min={1} />)}
      </FormItem>
      <Modal
        title={formatMessage({ id: 'app.base.picture-preview' })}
        visible={pictureModalVisible}
        onOk={() => setPictureModalVisible(false)}
        onCancel={() => setPictureModalVisible(false)}
        afterClose={() => setPictureModalVisible(false)}
        footer={null}
      >
        <img src={picturePreviewUrl} width={'100%'} />
      </Modal>
      {
        previewModelVisible && (
          <PreviewForm
            previewModelVisible={previewModelVisible}
            onVisibleModel={handlePreviewModalVisible}
            previewImg={previewImg}
          />
        )
      }
    </Modal>
  );
};

export default Form.create<ConfigFormProps>()(ConfigForm);
